# 为智慧热网的一网供温预测和评价功能 准备数据，写入Aimongdb
# 根据热指标模型计算

import datetime
import time
from pymongo import MongoClient
import requests
import pandas as pd
import moduleAiMongdb
import moduleGeneral




#取天气预报  # 智信天气微服务 给 multi模型用
def get_weather_data(city_code,in_h,time):
    print(in_h)
    print('开始获取气象数据')
    start_time_bj = datetime.datetime.strptime(time,'%Y-%m-%d %H:%M:%S')
    end_time_bj = start_time_bj + datetime.timedelta(hours=in_h)

    start_year = str(start_time_bj.year)
    start_month = str(start_time_bj.month)
    start_day = str(start_time_bj.day)
    start_hour = str(start_time_bj.hour)

    end_year = str(end_time_bj.year)
    end_month = str(end_time_bj.month)
    end_day = str(end_time_bj.day)
    end_hour = str(end_time_bj.hour)

    weather_start_time = start_year + '%24' + start_month + '%24' + start_day + '%24' + start_hour + '%3A' + '00' + '%3A' + '00'
    weather_end_time = end_year + '%24' + end_month + '%24' + end_day + '%24' + end_hour + '%3A' + '00' + '%3A' + '00'
    query_weather_future = 'http://114.215.46.56:18825/v1/weathers?city_id=%s&start_hour=%s&end_hour=%s'%( city_code,weather_start_time,weather_end_time)


    # print(query_weather_future)
    try:
        weather_records = requests.get(query_weather_future)
    except Exception as e:
        print('get weather_data have a error\n')
        print(e)

    if weather_records:

        weather_records.encoding = 'utf-8'
        weather_datas = weather_records.json()
        weather_dataframe = pd.DataFrame.from_records(weather_datas)
        # print(weather_dataframe)
    else:
        return []

    if weather_dataframe.shape[0] > in_h:
        # 删除nan行
        weather_dataframe.dropna(axis=0, how='any', inplace=True)

    df_weather = weather_dataframe[['img', 'temp', 'humidity', 'windpower', 'week','date']].copy()
    # 数字化
    # 工作日、非工作日
    week_mapping = {'星期一': 1, '星期二': 1, '星期三': 1, '星期四': 1, '星期五': 1, '星期六': 0, '星期日': 0}
    df_weather['week'] = df_weather['week'].map(week_mapping)

    # 将风力数字化
    windpower_mapping = {'1级': 1, '2级': 2, '3级': 3, '4级': 4, '5级': 5, '6级': 6, '7级': 7}
    df_weather['windpower'] = df_weather['windpower'].map(windpower_mapping)

    # 将天气img 改名为 weather
    df_weather.rename(columns={"img": 'weather'}, inplace=True)

    # 将日期拆分成 年月日，增加列
    # print('拆分日期')
    df_weather.date = pd.to_datetime(df_weather.date, format='%Y/%m/%d %H:%M')
    # 获取 日期数据 的年、月、日、时、分
    # weather_dataframe['year'] = weather_dataframe['date'].dt.year
    df_weather['month'] = df_weather['date'].dt.month
    df_weather['day'] = df_weather['date'].dt.day
    df_weather['hour'] = df_weather['date'].dt.hour

    # 删除日期列
    # print('del date')
    df_weather.drop(['date'], axis=1, inplace=True)
    # print('预处理后的气象数据：')

    # 改变顺序
    df_weather=df_weather[['month','day','hour','week','weather','temp','humidity','windpower']]



    return df_weather



def make_forecast_hourly(company_id,heating_source,workHour):

    #取天气数据
    weather=get_weather_data(217,1, workHour.strftime("%Y-%m-%d %H:%M:%S"))

    #进行预测
    heat_forecast=make_forecast(heating_source,workHour,weather)

    #写入预测结果数据库
    insert_forecast_result(heating_source,heat_forecast)

    print()




def make_forecast(heating_source,work_hour,weather):





    forefast_result=[]
    for index, row in weather.iterrows():
        # 查模型参数
        time = datetime.datetime(work_hour.year,int(row['month']),int(row['day']),int(row['hour']), 0, 0)
        heat_m = moduleAiMongdb.get_heat_from_mongdb(heating_source,time)

        print(time,row['temp'])  # 输出每一行
        x1 = float(0)
        x2 = float(-10)
        y1 = float(heat_m["heat_index_0"])
        y2 = float(heat_m["heat_index_10"])
        x=float(row['temp'])
        y=y1+(x-x1)*(y2-y1)/(x2-x1)
        k=5
        forefast_result.append([time,heating_source,y*k])


    print('气温：%s---耗热量：%s'%(x,y*k))
    return forefast_result


def insert_forecast_result(heating_source,heat_forecast):
    moduleAiMongdb.insert_forecast_mongdb_hourly(heating_source, heat_forecast)
    print()





# Press the green button in the gutter to run the script.
if __name__ == '__main__':

    company_id = 100073
    heating_source = '60f697431e05000018005548'


    # 初寒期
    # workHours = moduleGeneral.make_hours_list('2020-11-16 01:00:00', '2020-12-14 00:00:00')
    # for oneHour in workHours:
    #     work_datetime=datetime.datetime(int(oneHour[0]),int(oneHour[1]),int(oneHour[2]),int(oneHour[3]),0,0)
    #     make_forecast_hourly(company_id,heating_source,work_datetime)

    # 严寒期
    # workHours = moduleGeneral.make_hours_list('2020-12-14 00:00:00', '2021-02-04 00:00:00')

    # 天气数据，从1月13日开始有通化数据
    # workHours = moduleGeneral.make_hours_list('2021-01-14 00:00:00', '2021-02-04 00:00:00')

    # for oneHour in workHours:
    #     work_datetime=datetime.datetime(int(oneHour[0]),int(oneHour[1]),int(oneHour[2]),int(oneHour[3]),0,0)
    #     make_forecast_hourly(company_id,heating_source,work_datetime)

    # 末寒期
    workHours = moduleGeneral.make_hours_list('2021-03-14 00:00:00', '2021-03-17 00:00:00')
    for oneHour in workHours:
        work_datetime=datetime.datetime(int(oneHour[0]),int(oneHour[1]),int(oneHour[2]),int(oneHour[3]),0,0)
        make_forecast_hourly(company_id,heating_source,work_datetime)

